# greedy non-bipartite (continuous) matching

nbpGreedy=function(dMat=dMat,replace=F,seed=1005){
	n=dim(dMat)[1]
	set.seed(seed)
	xvec=sample(1:n,replace=F,size=n)
	
	outs=as.data.frame(matrix(NA,n,2))
	outs[,1]=xvec
	
	if(replace==F){
		smp=round(dim(dMat)[1]/2-.1)
		i=1
		while(!is.na(outs[i,1]) & i<=smp){
			mat=outs[i,1]
			xvec=xvec[c(which(xvec!=mat))]
			
			indx=xvec[which(dMat[xvec,mat]==min(dMat[xvec,mat]))]
			if(length(indx)>1){
				outs[i,2]=indx[sample(1:length(indx),size=1)]
			} else {
				outs[i,2]=indx	
			}
			
			outs=outs[c(which(outs[,1]!=outs[i,2])),]
			xvec=xvec[c(which(xvec!=outs[i,2]))]
			i=i+1
		}
		outs=as.data.frame(outs[which(!is.na(outs[,2])),])
	} else if(replace==T){
		for(i in 1:nrow(outs)){
			mat=outs[i,1]
			indx=xvec[which(dMat[,mat]==min(dMat[,mat][-c(mat)]))]
			if(length(indx)>1){
				outs[i,2]=indx[sample(1:length(indx),size=1)]
			} else {
				outs[i,2]=indx	
			}
		}
	}
	return(outs)
}
